package task;

import util.DBUtil;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Author: yuisama
 * @Date: 2022/6/10 13:45
 * @Description: 项目开始启动加载SQLite数据库，创建表
 */
public class DBInit {
    public static List<String> readSQL() {
        List<String> ret = new ArrayList<>();
        // 从类加载器获取文件输入流
        InputStream in = DBInit.class.getClassLoader().getResourceAsStream("init.sql");
        Scanner scanner = new Scanner(in);
        scanner.useDelimiter(";");
        while (scanner.hasNext()) {
            String str = scanner.next();
            if (str.contains("--")) {
                str = str.replace("--","");
            }
            ret.add(str);
        }
        return ret;
    }

    public static void init() {
        Connection connection = null;
        Statement statement = null;
        try {
            // 1.获取连接
            connection = DBUtil.getConnection();
            // 2.获取Statement
            statement = connection.createStatement();
            // 3.执行更新或修改
            List<String> sqls = readSQL();
            for (String sql : sqls) {
                System.out.println("执行SQL操作 : " + sql);
                statement.executeUpdate(sql);
            }
        } catch (SQLException e) {
            System.err.println("init method error!");
            e.printStackTrace();
        }finally {
            // 4.资源关闭
            DBUtil.close(statement);
        }
    }

    public static void main(String[] args) {
        List<String> list = readSQL();
        System.out.println(list);
    }
}
